// 整合service实现 收发接口统一入口
import { Callbacks } from '../callback.js';
import { sendCMD } from "../sendCMD";
// 根据key保存每个模块的对应数据
let serviceProtocolMap = new Map();
let notifyFuncsCollect = {};
let rspFuncsCollect = {};
let reconnectCollect = {};
let socketReadyCollect = {};
let callBackFuncCollect = {};

var ServiceModuleKey = {
  hwmService: 0x16, // 22
};

/**
 * 初始化模块部分非引用对象数据
 */
(function initState() {
  for (const key in ServiceModuleKey) {
    if (ServiceModuleKey.hasOwnProperty(key)) {
      reconnectCollect[key] = 0;
      socketReadyCollect[key] = false;
    }
  }
})();

/**
 * 定义协议对外接口
 */
export class ServiceProtocol {
  /**
   * @param {number} key 模块对应的key
   * @param {string} moduleName 模块名字
   * @param {function} onMessage 回调的处理函数
   */
  constructor(option) {
    for (const key in option) {
      if (option.hasOwnProperty(key)) {
        this[key] = option[key];
      }
    }
    serviceProtocolMap.set(this.key, this);
  }
  /**
   * @description 发送消息
   * @param {Object} data
   */
  sendMessage() { }
  /**
   * @description 统一的处理回调消息入口
   * @param {Object} data
   */
  handleServiceCallback(data) {
    try {
      console.log("handleServiceCallback",data);
      let _rspFuncs = rspFuncsCollect[this.key];
      let _notifyFuncs = notifyFuncsCollect[this.key];
      let _callBackType = data.data.notify_type;

      if(_callBackType === 0 && "function" === typeof _rspFuncs[data.data.sno]){
        _rspFuncs[data.data.sno](data);
        // 清除回调函数
        _rspFuncs[data.data.sno] = null;
      }else if (_callBackType === 1 && "object" === typeof _notifyFuncs[data.cmd]) {
        _notifyFuncs[data.cmd].fire(data);
      }
    } catch (e) {

    }
  }
  /**
   * @description 统一的发送消息入口
   * @param {Object} option
   */
  setRspFuncsAndSendMessage(option) {
    let { resolve, data, timeoutTime = 35000 } = option; // 大部分接口超时都是30秒，这边统一增加五秒
    let _moduleKey = this.key;
    let _rspFuncs = rspFuncsCollect[_moduleKey] || [];
    let _notifyFuncs = notifyFuncsCollect[_moduleKey] || [];
    rspFuncsCollect[_moduleKey] = _rspFuncs;
    notifyFuncsCollect[_moduleKey] = _notifyFuncs;
    let { cmd, sno } = data;
    let _timeoutTimer = setTimeout(() => {
        resolve({ data: { reason_code:-1 } });
    }, timeoutTime);

    let _rspFuncCommon = data2 => {
      clearTimeout(_timeoutTimer);
      data = null;
      resolve(data2);
    };
    _rspFuncs[sno] = _rspFuncCommon;
    this.sendMessage(data);
  }
  /**
   * @description 设置notify
   * @param {Object} data
   */
  setNotifyFunc(notify, func) {
    let _notifyFuncs = notifyFuncsCollect[this.key] || [];
    notifyFuncsCollect[this.key] = _notifyFuncs;
    if (!_notifyFuncs[notify]) {
      _notifyFuncs[notify] = Callbacks("unique");
    }
    _notifyFuncs[notify].empty().add(func); // 添加前先清空
  }
}

export class ServiceNativeProtocol extends ServiceProtocol {
  constructor(option) {
    super(option);
    return new Promise((resolve) => {
      resolve(this);
    });
  }

  sendMessage(data) {
    sendCMD(this.key, data);
  }
}

/**
 * 提供给原生的回调给js的接口, native模式使用
 */
window.notifyJsServiceCallback = (serviceKey, callbackString) => {
  dispatchServiceCallback(serviceKey, callbackString);
};

/**
 * native模式使用
 */
function dispatchServiceCallback(moduleKey, data) {
  let serviceProtocol = serviceProtocolMap.get(moduleKey);
  console.log("dispatchServiceCallback",serviceProtocolMap,moduleKey,data);
  serviceProtocol.handleServiceCallback(data);
  return;
}

/**
 * 构造函数路由
 */
export function getServiceProtocolClass() {
  return ServiceNativeProtocol;
}
